#!/usr/bin/ruby

require 'time'

class CCron
  @interval = 30 # => minutes

  def self.interval=(tm)
    @interval = tm
  end

  def self.interval
    @interval
  end

  def self.at(config, &block)
    params = config.split(/\s+/, 5)
    raise ArgumentError, "a few argument"  if params.length < 5

    prev_time = (Time.now - (@interval * 60)).strftime("%M %H %d %m %w").split(/\s/).map{|v| v.to_i}
    current_time = Time.now.strftime("%M %H %d %m %w").split(/\s/).map{|v| v.to_i}

    is_exec = true

    5.times do |i|
      next  if params[i] == '*'

      if params[i] =~ /([0-9]+)-([0-9]+)/
        min, max = $1.to_i, $2.to_i
#       puts "#{min} #{max}"
        unless CCron.check_range?(prev_time[i], min, max) || CCron.check_range?(current_time[i], min, max)
          is_exec = false
          break    
        end
      else
        unless CCron.check_range?(params[i].to_i, prev_time[i], current_time[i])
          is_exec = false
          break    
        end
      end
    end

    block.call if is_exec && !block.nil?

    is_exec
  end

  def self.check_range?(value, min, max)
#   puts "<check_range> #{value} => #{min}, #{max}"

	if min == max
      if min == value
        true
      else
        false
      end
	elsif min < max
      if min <= value && value <= max
        true
      else
        false
      end
    else
      unless max < value && value < min
        true
      else
        false
      end
    end
  end
end

